
import qr from "qr-image";
import { message } from "antd";
import { Permission, PermissionState } from "pao-aop";
import { Redirect } from "react-router";
import React from "react";
import { IndustryInternetSignAppStorage } from "./appStorage";
import { SIGN_KEY_PARAM, chCheck, capitalLetter } from "src/business/util_tool";
/** 行点击跳转事件 */
export function onRowSkipClick(props: any, record: any, index: number, target: string) {
    console.log('onRowClick: ', record);
    props.history!.push(target + `/${record.id}`);
}
/**
 * 把数组结构转换成Map结构
 * @param name_field 字段名
 * @param product_data 数据源
 */
export function change_structure(name_field: string, data: any): any {
    let map = new Map();
    if (data) {
        data!.map((row: any, index: number) => {
            map.set(row.id + '', row[name_field]);
        });
    }
    return map;
}
/**
 * 生成二维码
 */
export function build_qrCode(code?: string, callback?: any): any {
    let key: string | undefined = code;
    code = 'http://192.168.97.135:3000/sign-analysis?key=' + code;
    // code = 'https://ipsp.gdsinsing.com:8080/product-sign-py/' + code;
    var svg_string = qr.imageSync(code!, { type: 'svg' }) + '';
    // img.src = svg_string;
    let src = 'data:image/svg+xml;base64,' + window.btoa(unescape(encodeURIComponent(svg_string)));
    // console.log('src', src);
    // return src;
    create_text_code(
        src,
        callback,
        key);
}
/**
 * 重新生成带有文字的二维码照片
 */
export function create_text_code(source: any, callback: any, code: string | undefined) {
    let base64 = "";
    let width = 200, // image resize   压缩后的宽
        quality = 0.5, // image quality  压缩质量
        canvas = document.createElement("canvas"),
        drawer: any = canvas.getContext("2d");

    var image = new Image();
    image.src = source;
    image.onload = function () {
        canvas.width = width;
        canvas.height = width * (image.height / image.width);
        let text_height = 15;
        if (code!.length > 27 && code!.length < 53) {
            text_height += 15;
        } else if (code!.length > 53) {
            text_height += 32;
        }
        drawer.drawImage(image, 0, 0, canvas.width, canvas.height - text_height);
        drawer.font = "normal 12px arial";
        // drawer.fontWeight = '100px';
        drawer.textAlign = 'center';
        // drawer.fillStyle = "#008600";
        var wraptext = new WrapText();
        wraptext.text_handle(drawer, code!, 100, 200 - text_height + 10, width - 10, 14);
        // drawer.strokeText(code, 80, 160, 165);
        base64 = canvas.toDataURL("image/svg+xml", quality);
        callback(base64);
        console.log(base64);
    };
}
/**
 * canvas换行工具类
 */
export class WrapText {
    text_handle(thiz: any, text?: string, x?: number, y?: number, maxWidth?: any, lineHeight?: any): void {

        if (typeof text !== 'string' || typeof x !== 'number' || typeof y !== 'number') {
            return;
        }

        var context = thiz;
        var canvas = context.canvas;

        if (typeof maxWidth === 'undefined') {
            maxWidth = (canvas && canvas.width) || 200;
        }
        if (typeof lineHeight === 'undefined') {
            lineHeight = (canvas && parseInt(window.getComputedStyle(canvas).lineHeight!, 10)) || parseInt(window.getComputedStyle(document.body).lineHeight!, 10);
        }

        // 字符分隔为数组
        var arrText = text.split('');
        var line = '';

        for (var n = 0; n < arrText.length; n++) {
            var testLine = line + arrText[n];
            var metrics = context.measureText(testLine);
            var testWidth = metrics.width;
            if (testWidth > maxWidth && n > 0) {
                context.font = "normal 12px arial";
                // context.fontWeight = 'normal';
                context.strokeText(line, x, y);
                line = arrText[n];
                y += lineHeight;
            } else {
                line = testLine;
            }
        }
        context.font = "normal 12px arial";
        // context.fontWeight = 'normal';
        context.strokeText(line, x, y);
    }

}
/** 上传URL */
export const UPLOAD_URL = "http://192.168.97.135:3010/upload";

/** 路由URL */
export const ROUTE_PATH = {
    /** 品类路由 */
    categoryTemplate: "/category-template",
    changeCategoryTemplate: "/change-category-template",
    categoryTemplateDetail: "/category-template-detail",
    /** 外链路由 */
    externalLinks: "/externalLinks",
    changeExternalLinks: "/change-externalLinks",
    externalLinksDetail: "/externalLinks-detail",
    statisticalAnalysis: "/statistical-analysis",
    allSignView: "/all-sign-view",
    signPreview: '/sign-analysis',
    addRole: '/add-role',
    singleProductView: '/single-product',
    changeSingleProductView: '/change-single-product',
    companyTemplateView: '/company-templateView',
    singleProductDetailView: '/single-product-detail',
    changeCompanyTemplateView: '/change-company-templateView',
    companyTemplateDetail: '/company-template-detail',
    /** 安全路由 */
    rolePermission: '/role-permission',
    userManage: '/user-manage',
    userEditor: '/user-editor',
    login: '/login',
    bindPhone: '/bind-phone',
    modifyLoginPassword: '/modify-login-password',
    modifyMobile: '/modify-mobile',
    modifyEmail: '/modify-email',
    securitySettings: '/security-settings',
    Abnormity: '/abnormity',
    retrievePassword: '/retrieve-password',
    stencil: '/stencil',
    changeStencil: '/change-stencil',
    productClassify: '/product-classify',
    changeProductClassify: '/change-product-classify',
    productSign: '/product-sign',
    changeProductSign: '/change-product-sign',
    productSignDetail: '/product-sign-detail'
};

/** Match参数名称 */
export const SIGN_ID = "sign_id";
/** 路由参数名称 */
export const SIGN_ID_PARAM = `:${SIGN_ID}`;
/** 企业Match参数名称 */
export const COMPANY_ID = "company_id";
/** 企业路由参数名称 */
export const COMPANY_ID_PARAM = `:${COMPANY_ID}`;

/** 角色Match参数名称 */
export const ROLE_ID = 'role_id';
/** 角色路由参数名称 */
export const ROLE_ID_PARAM = `:${ROLE_ID}`;

/** 用户Match参数名称 */
export const USER_ID = 'user_id';
/** 用户路由参数名称 */
export const USER_ID_PARAM = `:${USER_ID}`;

/** 模版Match参数名称 */
export const STENCIL_ID = 'stencil_id';
/** 模版参数名称 */
export const STENCIL_ID_PARAM = `:${STENCIL_ID}`;
/** 产品分类Match参数名称 */
export const PRODUCT_CLASSIFY_ID = 'product_classify_id';
/** 产品分类参数名称 */
export const PRODUCT_CLASSIFY_ID_PARAM = `:${PRODUCT_CLASSIFY_ID}`;
/** 产品标识Match参数名称 */
export const PRODUCT_SIGN_ID = 'product_sign_id';
/** 产品标识参数名称 */
export const PRODUCT_SIGN_ID_PARAM = `:${PRODUCT_SIGN_ID}`;
// 压缩图片的方法
export function ontpys(img: any, callback: any) {
    let base64 = "";
    let width = 400, // image resize   压缩后的宽
        quality = 0.5, // image quality  压缩质量
        canvas = document.createElement("canvas"),
        drawer: any = canvas.getContext("2d");
    img.onload = function () {
        canvas.width = width;
        canvas.height = width * (img.height / img.width);
        drawer.drawImage(img, 0, 0, canvas.width, canvas.height);
        base64 = canvas.toDataURL("image/jpeg", quality);
        callback(base64);
    };
}
/**
 * let img=new Image()
 *   img.src = data.company_picture[0];
 *
 */

/** 上传前回调方法 */
export function beforeUpload(file: File) {
    console.log('file.type', file.type);
    const isImage = (file.type === 'image/jpeg' || file.type === 'image/png');
    if (!isImage) {
        message.error('你必须上传JPG/png格式的文件!');
    }
    const isLt1M = file.size / 1024 / 1024 < 1;
    if (!isLt1M) {
        message.error('图片大小必须小于1MB!');
    }
    return isLt1M && isImage;
}

/** 传真非中文验证 */
export function checkNoCh(rule: any, val: any, cb: any) {
    if (Array.isArray(val)) {
        for (const iterator of val) {
            if (iterator.context !== '' && chCheck(iterator.contents)) {
                cb("传真不能输入中文");
            }
        }
    }
    cb();
}

/** 标识验证 */
export function checkCode(rule: any, val: any, cb: any) {
    if (chCheck(val)) {
        cb("不能输入含有中文的标识码");
    }
    if (capitalLetter(val)) {
        cb("不能输入含有大写字母的标识码");
    }
    if (val === "") {
        cb("请输入标识");
    }
    if (val.length > 56) {
        cb("标识码过长");
    }
    cb();
}

/** 判断权限 */
export function isPermission(permission: Permission, company_id?: string) {
    let userRole = IndustryInternetSignAppStorage.getCurrentUserRoles();
    let companySign = IndustryInternetSignAppStorage.getCurrentCompanySign();
    // 判断是否拥有权限
    for (let role in userRole) {
        if (role) {
            for (let permissions in userRole[role]['permission']) {
                if (permission) {
                    if (userRole[role]['permission'][permissions]['permission'] === permission['permission']
                        && userRole[role]['permission'][permissions]['permission_state'] === PermissionState.forbid) {
                        return <Redirect to={ROUTE_PATH.Abnormity} />;
                    } else if (userRole[role]['permission'][permissions]['permission'] === permission['permission']
                        && userRole[role]['permission'][permissions]['permission_state'] === PermissionState.default) {
                        return <Redirect to={ROUTE_PATH.Abnormity} />;
                    }
                }

            }
        }
    }
    console.info(companySign !== undefined);
    // 判断企业id是否一致
    if (!companySign && company_id && companySign !== undefined) {
        if (companySign['id'] !== company_id) {
            return <Redirect to={ROUTE_PATH.Abnormity} />;
        }
    }
    return;
}

/** 自定义校验内容 */
export function handleConcent(rule: any, value: any[], callback: any) {
    console.log('check', value);
    const number = value ? value.length : 0;
    for (let i = 0; i < number; i++) {
        let obj: Object = value[i];
        for (const key in obj) {
            if (obj.hasOwnProperty(key)) {
                if (!obj[key]) {
                    callback('校验报错,类目信息不能为空');
                    return;
                }
            }
        }
    }
    callback();
    return;
}

export const changeCategoryTemplate = `${ROUTE_PATH.changeCategoryTemplate}/${SIGN_ID_PARAM}`;
export const companyTemplateDetail = `${ROUTE_PATH.companyTemplateDetail}/:${COMPANY_ID}`;
export const changeCompanyTemplateView = `${ROUTE_PATH.changeCompanyTemplateView}/:${SIGN_ID}`;
export const categoryTemplateDetail = `${ROUTE_PATH.categoryTemplateDetail}/${SIGN_ID_PARAM}`;
export const singleProductDetailView = `${ROUTE_PATH.singleProductDetailView}/${SIGN_ID_PARAM}`;
export const changeSingleProductView = `${ROUTE_PATH.changeSingleProductView}/${SIGN_ID_PARAM}`;
export const externalLinksDetail = `${ROUTE_PATH.externalLinksDetail}/${SIGN_ID_PARAM}`;
export const changeExternalLinks = `${ROUTE_PATH.changeExternalLinks}/${SIGN_ID_PARAM}`;
export const userEditor = `${ROUTE_PATH.userEditor}/${SIGN_KEY_PARAM}`;
export const addRole = `${ROUTE_PATH.addRole}/${SIGN_KEY_PARAM}`;
export function selectedKeys(pathname: string) {
    console.info(pathname);
    switch (pathname) {
        case ROUTE_PATH.companyTemplateDetail:
        case companyTemplateDetail:
        case changeCompanyTemplateView:
            return ROUTE_PATH.companyTemplateView;
        case ROUTE_PATH.categoryTemplate:
        case ROUTE_PATH.changeCategoryTemplate:
        case changeCategoryTemplate:
        case categoryTemplateDetail:
            return ROUTE_PATH.categoryTemplate;
        case ROUTE_PATH.singleProductDetailView:
        case singleProductDetailView:
        case changeSingleProductView:
        case ROUTE_PATH.changeSingleProductView:
            return ROUTE_PATH.singleProductView;
        case ROUTE_PATH.externalLinks:
        case ROUTE_PATH.changeExternalLinks:
        case externalLinksDetail:
        case changeExternalLinks:
            return ROUTE_PATH.externalLinks;
        case ROUTE_PATH.userManage:
        case ROUTE_PATH.userEditor:
        case userEditor:
            return ROUTE_PATH.userManage;
        case ROUTE_PATH.rolePermission:
        case ROUTE_PATH.addRole:
        case addRole:
            return ROUTE_PATH.rolePermission;
        case ROUTE_PATH.securitySettings:
        case ROUTE_PATH.modifyLoginPassword:
        case ROUTE_PATH.modifyMobile:
        case ROUTE_PATH.modifyEmail:
            return ROUTE_PATH.securitySettings;
        case ROUTE_PATH.changeStencil:
            return ROUTE_PATH.stencil;
        default:
            return pathname;
    }
}